package cn.wlinker.video.monitor.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import cn.wlinker.video.monitor.config.StaticFileConfig;
import lombok.SneakyThrows;
import org.springframework.util.Assert;

import java.net.URL;
import java.util.Objects;

/**
 * 工具类
 *
 * @author gxsjx
 * @version 1.0
 * @date 2025/5/4
 * Copyright © wlinker.cn
 */
public class CommonKitUtils {

    private static Boolean isNotJar() {
        URL url = CommonKitUtils.class.getClassLoader().getResource("");
        assert url != null;
        String protocol = url.getProtocol();
        return !"jar".equals(protocol);
    }

    /**
     * 获取项目webapp目录
     *
     * @return
     */
    @SneakyThrows
    public static String getLibPath() {
        OsInfo osInfo = SystemUtil.getOsInfo();
        String rightPath = "";
        String baseFileDir = StaticFileConfig.getBaseFileDir();
        if (osInfo.isLinux()) {
            //根据linux中的依赖包的实际路径配置
            rightPath = "lib/hik/libhcnetsdk.so";
        } else if (osInfo.isWindows()) {
            if (isNotJar()) {
                baseFileDir = Objects.requireNonNull(CommonKitUtils.class.getClassLoader().getResource("")).getPath().substring(1);
                rightPath = "lib\\hik\\win\\HCNetSDK.dll";
            } else {
                rightPath = "lib\\hik\\HCNetSDK.dll";
            }
        }
        return getPath(rightPath, baseFileDir);
    }

    /**
     * 获取项目webapp目录
     *
     * @return
     */
    @SneakyThrows
    public static String getPlayLibPath() {
        OsInfo osInfo = SystemUtil.getOsInfo();
        String rightPath = "";
        String baseFileDir = StaticFileConfig.getBaseFileDir();
        if (osInfo.isLinux()) {
            //根据linux中的依赖包的实际路径配置
            rightPath = "lib/hik/libPlayCtrl.so";
        } else if (osInfo.isWindows()) {
            if (isNotJar()) {
                baseFileDir = Objects.requireNonNull(CommonKitUtils.class.getClassLoader().getResource("")).getPath().substring(1);
                rightPath = "lib\\hik\\win\\PlayCtrl.dll";
            } else {
                rightPath = "lib\\hik\\PlayCtrl.dll";
            }
        }
        return getPath(rightPath, baseFileDir);
    }

    private static String getPath(String rightPath, String baseFileDir) {
        String path = baseFileDir + rightPath;
        boolean exist = FileUtil.exist(path);
        int lastIndex = path.lastIndexOf("\\");
        if (lastIndex == -1) {
            lastIndex = path.lastIndexOf("/");
        }
        String fileDir = path.substring(0, lastIndex);
        if (Boolean.FALSE.equals(exist)) {
            FileUtil.mkdir(fileDir);
        }
        Assert.isTrue(exist, "Please upload hik lib files to the directory: " + fileDir);
        return path;
    }

}
